package apis

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"fmt"
	"os"
	"io"
	"log"
	"path/filepath"
	"github.com/satori/go.uuid"
)

//文件上传处理函数
func UpLoadApi(c *gin.Context) {
	//gin将het/http包的FormFile函数封装到c.Request
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.String(http.StatusBadRequest, fmt.Sprintf("get file err : %s", err.Error()))
		return
	}
	//获取文件名
	ext := filepath.Ext(header.Filename)
	name, _ := uuid.NewV4()
	filename := name.String() + ext
	//写入文件
	//out, err := os.Create("/home/gopath/src/tylnmall/file/" + filename)
	out, err := os.OpenFile("/home/gopath/src/tylnmall/file/" + filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
	//defer f.Close()
	//fmt.Println(f.Stat())
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()
	_, err = io.Copy(out, file)
	if err != nil {
		log.Fatal(err)
	}
	filepath := filename
	//以json格式返回文件存放路径
	c.JSON(http.StatusOK, gin.H{"filepath": filepath})
}